package module.modbus.ascii;

import com.serotonin.modbus4j.ModbusMaster;
import gnu.io.CommPortIdentifier;
import gnu.io.UnsupportedCommOperationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.SerialTool;

/**
 * @author bingo
 * @Description
 * @Date 2018/8/15
 */
public class AsciiStartThread implements Runnable {

    private ModbusAscii modbusAscii;

    public  static   boolean isLock = true;

    private Logger logger = LoggerFactory.getLogger(AsciiStartThread.class);

    public AsciiStartThread() {
      modbusAscii = new ModbusAscii();
    }

    public ModbusAscii getModbusAscii(){
        return  modbusAscii;
    }

    @Override
    public void run() {
        modbusAscii.open(SerialTool.getCommPortIdentifier("COM1"));
        short[]  values = {1};
        for(int i=1;i<=3;i++) {
            modbusAscii.send(1, 3, 0, values);
            try {
                Thread.sleep(2000);
                if (modbusAscii.getMessage() == null) {
                    logger.info("从机没有应答,正在尝试第{}次发送",i+1);

                }else {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if(modbusAscii.getMessage()==null){
            logger.info("从机没有应答,请检测发送报文格式，或是否时机器故障");
            AsciiStartThread.isLock = false;
        }else{
            logger.info("succcess");
        }

    }




}
